26. Remove Duplicates from Sorted Array
https://leetcode.com/problems/remove-duplicates-from-sorted-array/description
Definition
Intuition
The idea is to find the next element which is different from current element . Since the list is already sorted, it is guaranteed that . Thus, when , we should apply these operations:
These steps repeats until , e.g., when is still a valid index.
Ilustration
Initial state
and starts pointing to the first and second elements respectively. It is safe to make point to the second element even for a list of a single element because the stop condition is . For lists of size 1, this condition will break and the algorithm stops because .
1st iteration
moves forward trying to find an element other than
2rd Iteration
moves forward and now points to a different element
Now we copy to and increment both pointers
3rd Iteration
moves forward and now points to a different element
Now we copy to and increment both pointers
4th Iteration
Since and , the algorithm finishes and returns the resulting list size, in this case it is . Thus, the final response is:
1 2 3 2 2 3 3
Implementation
Click to reveal implementation
class Solution:
def removeDuplicates(self, nums: list[int]) -> int:
left_index, right_index = 0, 1
n = len(nums)
while right_index < n:
left, right = nums[left_index], nums[right_index]
if left != right:
left_index += 1
nums[left_index] = right
right_index += 1
return left_index + 1
Tests
import pytest
from .solution import Solution
@pytest.mark.parametrize('numbers,expected', [
([1, 1, 1, 2, 2, 3, 3], [1, 2, 3])
])
def test_solution(numbers, expected):
new_size = Solution().removeDuplicates(numbers)
assert numbers[:new_size] == expected
Time complexity
Since the list is being completely iterated from left to right through pointer , the complexity is
Space complexity
Since the list is being modified in-place and no other allocations besides auxiliary variables are made, the complexity is